#include<stdio.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include<sys/types.h>
#define ERR_EXIT(m) do{ perror(m);exit(EXIT_FAILURE);}while(0)
#define SIZE 1024
int main(void)
{
    int shmid;
    char *shmaddr;
    struct shmid_ds buf;
    int flag=0;
    pid_t pid;

    shmid = shmget(IPC_PRIVATE,SIZE,IPC_CREAT|0600);

    if( shmid == -1)
        ERR_EXIT("shmget");
       
    pid = fork();

    if( pid == 0 )
    {
        shmaddr = (char *)shmat(shmid,NULL,0);
        if( shmaddr == -1)
            ERR_EXIT("shmat");
        strcpy(shmaddr,"这个是子进程\n");
        shmdt( shmaddr);
        return 0;
    }
    else if( pid == -1 )
    {
        shmctl(shmid,IPC_RMID,NULL);
        ERR_EXIT("fork");

    }
    else
    {
        flag = shmctl(shmid,IPC_STAT,&buf);
        if( flag == -1)
            ERR_EXIT("shmctl");
        printf("shm_segsz = %d bytes \n",buf.shm_segsz);
        printf("parent pid = %d ,shm_cpid = %d \n",getpid(),buf.shm_cpid);
        printf("child pid = %d shm_lpid = %d\n",pid,buf.shm_lpid);
        shmaddr = (char *)shmat(shmid,NULL,0);

        if( shmaddr == -1)
            ERR_EXIT("parent shmat");
        printf("%s",shmaddr);
        shmdt( shmaddr);
        shmctl(shmid,IPC_RMID,NULL);
    }
    



    ERR_EXIT("main");
    shmget(333,1024,IPC_PRIVATE);
}